<template>
  <div>
    <el-cascader
      :props="config"
      filterable
      clearable
      separator=""
      v-model="selectedAddress"
      :options="options"
      :style="{ width: props.width, marginBottom: '20px' }"
    />
    <el-input
      type="textarea"
      v-model="detailAddress"
      placeholder="请输入详细地址"
    />
  </div>
</template>

<script setup>
import { getAdderssTree } from '@/api/address'
import { ref, watch } from 'vue'

const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
  width: {
    type: String,
    default: '100%',
  },
})

const emit = defineEmits(['update:modelValue'])

const selectedAddress = ref([])
const detailAddress = ref('')
const options = ref([])

// 将modelValue解析为选中地址和详细地址
watch(
  () => props.modelValue,
  (value) => {
    const [address, detail] = value.split(' ')
    selectedAddress.value = address ? address.split(',') : []
    detailAddress.value = detail || ''
  },
  { immediate: true },
)

// 监听地址变化，更新v-model
watch([selectedAddress, detailAddress], () => {
  const address = selectedAddress.value.join(',')
  const detail = detailAddress.value
  emit('update:modelValue', `${address} ${detail}`.trim())
})

// 获取地址树数据
getAdderssTree().then((result) => {
  options.value = result.data
})

const config = {
  value: 'addressName',
  label: 'addressName',
}
</script>
